(function () {
    console.log("dcs历史数据文件");
    let now_open_diag = {}
    now_open_diag.API_URL = ''
    document.getElementById("todayTimer").innerHTML = moment(new Date()).format('YYYY-MM-DD HH:mm:ss')

    // 虚拟 dom 生成真实 dom -- 低配版（无diff算法版）
    function render(obj) {
        const {
            tagName,
            children,
            className,
            attrs
        } = obj;
        const dom = document.createElement(tagName);
        if (className) {
            dom.className = className;
        }
        if (attrs) {
            for (let key in attrs) {
                if (key.startsWith('on')) {
                    dom[key.toLocaleLowerCase()] = attrs[key];
                } else {
                    dom.setAttribute(key, attrs[key]);
                }
            }
        }
        if (children && children.length > 0) {
            if (typeof children == 'string') {
                const text = document.createTextNode(children);
                dom.appendChild(text);
            } else {
                children.forEach(item => {
                    dom.appendChild(render(item));
                })
            }
        }
        return dom;
    }

    function $(el, all = false) {
        if (all) return document.querySelectorAll(el);
        return document.querySelector(el);
    }

    function Request(baseUrl = '', time = 1000) {
        this.baseUrl = baseUrl;

        function request(url, option = {}) {
            return new Promise(async (resolve, reject) => {
                try {
                    const response = await fetch(baseUrl + url, option);
                    if (response.status == '200') {
                        const data = await response.json();
                        if (data.code == '200') {
                            resolve(data);
                        } else {
                            reject(data.message || '请求失败');
                        }
                    } else {
                        reject(response);
                    }
                } catch (e) {
                    reject(e);
                }
            })
        }

        this.post = function (url, data) {
            return request(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(data)
            })
        }

        this.get = function (url) {
            return request(url, {
                method: 'GET'
            })
        }
    }


    Request.createRequest = function (baseUrl) {
        return new Request(baseUrl);
    }

    let myEcharts = null;

    const COLORS = ['#09d2c0', '#f2c505', '#52d009', '#08ecec', '#52d009'];

    let DESC = ['A1火焰燃烧温度', 'A1火焰着火距离', 'A1煤粉分配率', 'A1煤粉颗粒细度']

    const CHARTDOM = $('#graph_canvas');

    const request = Request.createRequest(now_open_diag.API_URL);

    myEcharts = echarts.init(CHARTDOM);

    // 保存下拉框选的值
    let changeValue = ["负荷"];

    const reactive = {
        selectData: [],
        tableData: [],
        data: []
    }

    let option = {
        // title: {
        //     text: '动态曲线图',
        //     textStyle: {
        //         color: '#9bdef0'
        //     }
        // },
        grid: {
            x2: '20%'
        },
        legend: {
            data: changeValue,
            textStyle: {
                color: '#9bdef0'
            }
        },
        xAxis: {
            type: 'category',
            boundaryGap: false,
            data: changeValue,
            axisLabel: {
                color: "#fff"
            }
        },
        tooltip: {
            trigger: 'axis', // 有3个属性值 axis   item   none
            axisPointer: {
                type: 'cross',
                label: {
                    backgroundColor: '#6a7985' //配置展示方块的背景颜色
                }
            }
        },
        yAxis: {
            type: 'value'
        },

        dataZoom: [{
            type: 'inside', // 放大和缩小
            orient: 'vertical',
        }, {
            type: 'inside',
        }],
        series: [

        ]
    };

    // 监听数据变化，在set时操作业务逻辑
    const proxy = new Proxy(reactive, {
        set(target, key, value) {
            target[key] = value;
            // console.log(target, key, value)
            if (key == 'tableData' && value.length > 0) {
                const list = creatTableVirtual();
                // console.log(list)
                renderTable(list);
            } else if (key == 'data' && value.length > 0) {
                createEcharts();
            } else {
                const list = creatTableVirtual();
                renderTable(list);
            }
            return true
        },
        get(target, key) {
            return target[key];
        }
    })

    // 初始化表单数据
    request.get('/api/sjdl/dcsdata/select', {}).then(res => {

        res.data.sort(function (a, b) {
            // console.log(a, b);
            return a.id - b.id
            // return (a.pointName + '').localeCompare(b.pointName + '')
        })
        console.log(res.data);
        proxy.selectData = res.data;
    })

    function initTabledata(isReset) {
        const mprenow = moment(new Date()).subtract('2', 'minutes').format('YYYY-MM-DD HH:mm:ss')
        const mnow = moment(new Date()).format('YYYY-MM-DD HH:mm:ss');
        const mprenows = moment(new Date()).subtract('4', 'second').format('YYYY-MM-DD HH:mm:ss')
        const domList = $('.date_input', true);
        // console.log(domList[0], typeof domList[0].value);
        domList[0].value ? "" : domList[0].value = mprenow;
        domList[1].value ? "" : domList[1].value = mnow;
        domList[2].value ? "" : domList[2].value = 1;
        isReset ? (domList[0].value = mprenow, domList[1].value = mnow, domList[2].value = 1) : ''
        const valueList = [domList[0].value, domList[1].value, domList[2].value || 1];
        // lsLoader(" 加载中....");
        const loadingDiv = document.createElement('div');
        loadingDiv.className = 'loading';
        loadingDiv.innerText = '加载中...';
        document.body.appendChild(loadingDiv);
        request.post(`/api/sjdl/dcsdata/dcshistory`, {
            "endTime": valueList[1].replaceAll('-', '-').replaceAll('T', ' '),
            "interval": valueList[2],
            "pointIndexList": changeValue,
            //  "pointIndexList": ["A1燃烧稳定性"],
            "startTime": valueList[0].replaceAll('-', '-').replaceAll('T', ' ')
        }).then(res => {
            console.log(res.data)
            // res.data.map((item, index) => ({// proxy.selectData.find(iitem => iitem.pointName == item.pointName).pointDesc
            //     ...item,
            //     pointDesc: DESC[index]
            // }));
            // console.log(res.data,proxy.tableData)
            loadingDiv.innerText = res.message;
            setTimeout(function () {
                document.body.removeChild(loadingDiv)
            }, 1000)
            res.data.forEach((item, index, obj) => {
                item[changeValue[index]].pointDesc = changeValue[index]
            })
            proxy.tableData = res.data
            proxy.data = res.data


        }).catch(res => {
            loadingDiv.innerText = '加载失败';
            setTimeout(function () {
                document.body.removeChild(loadingDiv)
            }, 1000)
            // removeLoader()
        })
    }
    let timsStover = false
    function initValue(isReset) {


        const mprenow = moment(new Date()).subtract('2', 'minutes').format('YYYY-MM-DD HH:mm:ss')
        const mnow = moment(new Date()).format('YYYY-MM-DD HH:mm:ss');
        const domList = $('.date_input', true);

        domList[0].value ? "" : domList[0].value = mprenow;
        domList[1].value ? "" : domList[1].value = mnow;
        domList[2].value ? "" : domList[2].value = 1;
        isReset ? (domList[0].value = mprenow, domList[1].value = mnow, domList[2].value = 1) : ''
        const valueList = [domList[0].value, domList[1].value, domList[2].value || 1];
        // lsLoader(" 加 载 中....");

        const loadingDiv = document.createElement('div');
        if (timsStover === false) {
            loadingDiv.className = 'loading';
            loadingDiv.innerText = '加载中...';
            document.body.appendChild(loadingDiv);
        }

        request.post(`/api/sjdl/dcsdata/dcshistory`, {
            "endTime": valueList[1].replaceAll('-', '-'),
            "interval": valueList[2],
            "pointIndexList": changeValue,
            //  "pointIndexList": ["A1燃烧稳定性"],
            "startTime": valueList[0].replaceAll('-', '-')
        }).then(res => {
            console.log(res.data);
            proxy.tableData = res.data
            // .map((item, index) => ({// proxy.selectData.find(iitem => iitem.pointName == item.pointName).pointDesc
            //     ...item,
            //     pointDesc: DESC[index]
            // }));
            loadingDiv.innerText = res.message;
            if (timsStover === false) {
                setTimeout(function () {
                    document.body.removeChild(loadingDiv)
                }, 1000)
            }
            res.data.forEach((item, index, obj) => {
                item[changeValue[index]].pointDesc = changeValue[index]
            })
            proxy.data = res.data
            // .map((item, index) => ({//DESC[index]
            //     ...item,
            //     pointDesc: DESC[index]
            // }));
            setInterval(() => {
                // removeLoader()
            }, 500)
            timsStover = false

        }).catch(res => {
            loadingDiv.innerText = '加载失败...';
            setTimeout(function () {
                document.body.removeChild(loadingDiv)
            }, 1000)
            // removeLoader()
        })
    }


    // 创建表格
    function creatTableVirtual() {
        const tableData = [...proxy.tableData];
        const objList = [];
        tableData.forEach((c, index) => {

            let name = Object.keys(c)[0];

            const item = c[name];
            console.log(item);
            const obj = {};
            obj.tagName = 'tr';
            obj.attrs = {
                rowIndex: index
            }
            obj.children = [{
                tagName: 'td',
                attrs: {
                    rowindex: index,
                    style: `background-color: ${COLORS[index]}`
                },
                children: [{
                    tagName: 'select',
                    attrs: {
                        class: 'table-select',
                        value: name,
                        rowindex: index,
                        onChange: (e) => {
                            const text = proxy.selectData.find(citem => citem.dcsDesc == e.target.value).dcsDesc;
                            changeValue[index] = e.target.value;
                            // DESC[index] = text;
                            $(`.table-desc-${name}`).innerHTML = text;
                            $('.btn_select').onclick()
                        }
                    },
                    children: [
                        ...proxy.selectData.map(titem => ({
                            tagName: 'option',
                            attrs: name == titem.dcsDesc ? {
                                key: titem.dcsDesc,
                                value: titem.dcsDesc,
                                selected: true
                            } : {
                                key: titem.dcsDesc,
                                value: titem.dcsDesc,
                            },
                            children: titem.dcsName + " " + titem.dcsDesc
                        }))
                    ]
                }],
            },
            {
                tagName: 'td',
                // children: item.dcsDesc,
                children: name,
                className: `table-desc table-desc-${name}`,
                attrs: {
                    key: item.name,
                    // key:name
                }
            },
            {
                tagName: 'td',
                children: item.minValue.toFixed(2) + ''
            },
            {
                tagName: 'td',
                children: item.maxValue.toFixed(2) + ''
            },
            {
                tagName: 'td',
                children: item.average.toFixed(2) + ''
            },
            {
                tagName: 'td',
                children: [{
                    tagName: 'button',
                    className: 'btn btn-danger',
                    children: '删除',
                    attrs: {
                        rowindex: index,
                        onClick: (e) => {
                            if (changeValue.length == 1) {
                                alert('至少需要一个点位');
                                return;
                            }
                            proxy.tableData = proxy.tableData.filter((item, index) => index != e.target.getAttribute('rowindex'));
                            changeValue.splice(e.target.getAttribute('rowindex'), 1);
                            //DESC.splice(e.target.getAttribute('rowindex'), 1);
                            option.yAxis.splice(e.target.getAttribute('rowindex'), 1);
                            initTabledata();
                            myEcharts.clear();
                            proxy.data = proxy.data.filter((item, index) => index != e.target.getAttribute('rowindex'));
                            myEcharts.setOption(option);
                        }
                    }
                }]
            }
            ];
            objList.push(obj);
        })

        objList.push({
            tagName: 'tr',
            children: [{
                tagName: 'td',
                attrs: {
                    colspan: '6',
                },
                children: [{
                    tagName: 'button',
                    className: 'btn_add w-full',
                    children: '添加',
                    attrs: {
                        onClick: () => {

                            if (changeValue.length >= 4) {
                                alert('最多只能添加4个点位');
                                return;
                            }
                            const list = proxy.tableData;
                            const index = proxy.selectData.findIndex(item => changeValue[changeValue.length - 1] == item.dcsDesc);
                            const name = proxy.selectData[index + 1].dcsDesc;
                            const desc = proxy.selectData[index + 1].dcsDesc;
                            DESC.push(proxy.selectData[index + 1].dcsDesc);
                            changeValue.push(name);

                            list.push({
                                [name]: {
                                    "minValue": 0,
                                    "maxValue": 0,
                                    "average": 0,
                                    "pointDesc": name
                                },
                                "dcsDesc": name
                            });

                            // option.yAxis.push({
                            //     type: 'value',
                            //     name: desc,
                            //     position: 'left',
                            //     offset: 0,
                            //     nameTextStyle: {
                            //         color: '#df676a'
                            //     },
                            //     axisLabel: {
                            //         formatter: `{value}`
                            //     }
                            // });
                            proxy.tableData = list;

                            initTabledata();
                        }
                    }
                }]
            }]
        })
        return objList;
    }

    // 渲染表格
    function renderTable(list) {
        if ($('#table_container').children.length > 0) {
            $('#table_container').removeChild($('#table_container').children[0]);
        }

        const obj = {
            tagName: 'table',
            className: 'table table-bordered w-full ',
            attrs: {
                border: '2',
                cellspacing: '0',
            },
            children: [{
                tagName: 'thead',
                children: [{
                    tagName: 'tr',
                    children: [{
                        tagName: 'th',
                        children: '点位名称',
                    },
                    {
                        tagName: 'th',
                        children: '点位描述',
                    },
                    {
                        tagName: 'th',
                        children: '最小值',
                    },
                    {
                        tagName: 'th',
                        children: '最大值',
                    },
                    {
                        tagName: 'th',
                        children: '平均值',
                    },
                    {
                        tagName: 'th',
                        children: '操作',
                    }
                    ],
                },],
            },
            {
                tagName: 'tbody',
                children: list,
            }
            ]
        }

        $('#table_container').appendChild(render(obj));
    }

    // 查询按钮
    $('.btn_select').onclick = function () {
        const newArr = Array.from(new Set(changeValue));
        if (newArr.length < changeValue.length) {
            alert('点位名称不能重复');
            return;
        }
        const params = {};
        $('.date_input', true).forEach((item, index) => {
            if (index == 0) {
                params['startTime'] = moment(item.value).format('YYYY/MM/DD HH:mm:ss');
            } else if (index == 1) {
                params['endTime'] = moment(item.value).format('YYYY/MM/DD HH:mm:ss');
            } else {
                params['interval'] = item.value;
            }
        });
        // lsLoader(" 加 载 中...");
        const loadingDiv = document.createElement('div');
        loadingDiv.className = 'loading';
        loadingDiv.innerText = '正在查询...';
        document.body.appendChild(loadingDiv);

        request.post(`/api/sjdl/dcsdata/dcshistory`, {
            ...params,
            pointIndexList: changeValue
        }).then(res => {
            // proxy.tableData = res.data
            // .map((item, index) => ({
            //     ...item,
            //     pointDesc: DESC[index]
            // }));
            console.log(res);
            loadingDiv.innerText = res.message;
            setTimeout(function () {
                document.body.removeChild(loadingDiv)
            }, 1000)
            res.data.forEach((item, index, obj) => {
                item[changeValue[index]].pointDesc = changeValue[index]
            })
            proxy.data = res.data
            // .map((item, index) => ({
            //     ...item,
            //     pointDesc: DESC[index]
            // }));
            createEcharts();
            // removeLoader()
        }).catch(err => {
            loadingDiv.innerText = '查询失败';
            setTimeout(function () {
                document.body.removeChild(loadingDiv)
            }, 1000)
            // removeLoader()
        })
    }

    // 重置按钮
    $('.btn_reset').onclick = function () {
        initValue(true);
    }

    // 导出按钮
    $('.btn_export').onclick = function () {
        const loadingDiv = document.createElement('div');
        loadingDiv.className = 'loading';
        loadingDiv.innerText = '正在导出...';
        document.body.appendChild(loadingDiv);
        const params = {};
        $('.date_input', true).forEach((item, index) => {
            if (index == 0) {
                params['startTime'] = moment(item.value).format('YYYY/MM/DD HH:mm:ss');
            } else if (index == 1) {
                params['endTime'] = moment(item.value).format('YYYY/MM/DD HH:mm:ss');
            } else {
                params['interval'] = item.value;
            }
        });
        fetch(`${now_open_diag.API_URL}/spf/visit/exportHistroyData`, {
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                ...params,
                pointIndexList: changeValue,
            }),
            method: 'POST'
        }).then(res => {
            return res.blob()
        }).then(async res => {
            const url = await URL.createObjectURL(res);
            const aEle = document.createElement('a');
            aEle.href = url;
            aEle.style.display = 'none';
            aEle.download = "历史数据.xlsx";
            aEle.target = '_blank';
            document.body.appendChild(aEle);
            aEle.click();
            document.body.removeChild(aEle);
            URL.revokeObjectURL(url);
            setTimeout(function () {
                document.body.removeChild(loadingDiv)
            }, 1000)
        })
        // request.post(`/spf/visit/exportHistroyData`, {
        //     ...params,
        //     pointIndexList: changeValue,
        //     responseType: 'blob'
        // }).then(res => {
        //     // window.open(res.result.url);
        //     console.log(res, 1)
        //     window.open('http://example.com/download', '_blank');
        //     const adom = document.createElement('a');
        //     adom.style.display = 'none';
        //     adom.href = res.result.url;
        //     adom.download = res.result.fileName;
        //     document.body.appendChild(adom);
        //     adom.click();
        //     document.body.removeChild(adom);
        //     document.body.removeChild(loadingDiv);
        // }).catch(err => {
        //     loadingDiv.innerText = err;
        //     setTimeout(function () {
        //         document.body.removeChild(loadingDiv)
        //     }, 1000)
        // })
    }
    // echarts 逻辑
    function createEcharts() {
        myEcharts.clear()
        const legend = [];
        option.series = proxy.data.map((item, index) => {

            const key = Object.keys(item)[0];
            const obj = {};
            obj.name = item[key].pointDesc;
            obj.type = 'line';
            // obj.yAxisIndex = index;
            obj.itemStyle = {
                color: COLORS[index]
            };
            if (item[key].dataList.length !== 0) {
                const dataList = item[key].dataList
                item[key].dataList.filter((citem, index) => index % 10 === 0)
                obj.data = dataList.map(citem => {
                    return {
                        value: [moment(citem.pointTime).format('YYYY-MM-DD HH:mm:ss'), citem[key]]
                    };
                });
                obj.data.sort((a, b) => a.value[0].localeCompare(b.value[0]) || a.value[0].localeCompare(b.value[0]));
                dataList.sort((a, b) => a.pointTime.localeCompare(b.pointTime) || a.pointTime.localeCompare(b.pointTime));
                option.xAxis.data = dataList.map(citem => moment(citem.pointTime).format('YYYY-MM-DD HH:mm:ss'));
                // option.xAxis.yAxisIndex = index;
                // console.log(item[key].pointDesc, legend);
                legend.push(item[key].pointDesc);
                return obj;
            }

        });
        option.legend.data = legend;
        option.color = COLORS;
        // option.yAxis = proxy.data.map((citem, index) => {
        //     let yobj = {}
        //     for (const key in citem) {
        //         //console.log(key);
        //         if(citem[key].dataList.length!==0){
        //             const element = citem[key];
        //             for (const key1 in element) {
        //                 if (key1 == "pointDesc") {
        //                     yobj = {
        //                         type: 'value',
        //                         //name: element.pointDesc,
        //                         position: index == 0 ? 'left' : "right",
        //                         offset: index * 70,
        //                         nameTextStyle: {
        //                             color: COLORS[index]
        //                         },
        //                         axisLabel: {
        //                             formatter: `{value}`
        //                         },
        //                         axisLine: {
        //                             show: true,
        //                             lineStyle: {
        //                                 color: COLORS[index]
        //                             }
        //                         }
        //                     }
        //                 }

        //             }
        //         }

        //     }
        //     return yobj;
        // })
        console.log(option)
        myEcharts.setOption(option);
    }



    const initEvent = (str) => { //
        //获取事件元素
        let oFootBtns = document.getElementById(str).children //底部菜单 btns
        if (str == "zbf_foot_btns") {
            now_open_diag.username == "admin" ? "" : oFootBtns[oFootBtns.length - 1].style.display = "none"
            // now_open_diag.username == "admin" ? "" : oFootBtns[oFootBtns.length - 2].style.display = "none"
        }
        for (let i = 0; i < oFootBtns.length; i++) {
            oFootBtns[i].onclick = () => {
                for (let ii = 0; ii < oFootBtns.length; ii++) {
                    oFootBtns[ii].className = ""
                }
                oFootBtns[i].className = "active"
                if (str == "zbf_r_btns") {
                    if (i == 8) {
                        for (let o = 6; o < 14; o++) {
                            scene.children[2].children[o].visible = false
                        }
                    } else {
                        scene.children[2].children[13 - i].visible = !scene.children[2].children[13 - i].visible
                    }
                } else {
                    function closeDiag() {
                        // timer ? clearInterval(timer) : ""
                        oTodayTimer ? clearInterval(oTodayTimer) : ""
                        // var tab_titlenodes = document.getElementsByClassName('ls_tabtitle')[0].getElementsByTagName('li');
                        // onCloseTab(tab_titlenodes[now_open_diag.index].childNodes[1].childNodes[0])
                    }
                    switch (i) {
                        case 0:
                            closeDiag()
                            setTimeout(() => {
                                window.location.href = "/index.html"
                            }, 200)
                            break;
                        case 1:
                            closeDiag()
                            setTimeout(() => {
                                // openFM("全炉膛温度场", 11, "SJDL_IFS_DATA.prj", "全炉膛温度场")
                                window.location.href = "/quanlutang.html"
                            }, 200)

                            break;
                        case 2:
                            closeDiag()
                            setTimeout(() => {
                                // openFM("横截面", 6, "SJDL_IFS_DATA.prj", "横截面")
                                window.location.href = "/hjm.html"
                            }, 200)

                            break;
                        case 3:
                            closeDiag()
                            setTimeout(() => {
                                // openFM("燃烧稳定性监测", 7, "SJDL_IFS_DATA.prj", "燃烧稳定性监测")
                                window.location.href = "/ranshaowendingxing.html"
                            }, 200)

                            break;
                        case 4:
                            closeDiag()
                            setTimeout(() => {
                                // openFM("煤粉分配率", 9, "SJDL_IFS_DATA.prj", "煤粉分配率")
                                window.location.href = "/meifen.html"
                            }, 200)

                            break;
                        case 5:
                            closeDiag()
                            setTimeout(() => {
                                // openFM("煤粉颗粒度分布", 8, "SJDL_IFS_DATA.prj", "煤粉颗粒度分布")
                                window.location.href = "/main/dcimgs/gl/main.html"
                            }, 200)

                            break;
                        case 6:
                            closeDiag()
                            setTimeout(() => {
                                // openFM("预警信息", 12, "SJDL_IFS_DATA.prj", "预警信息")
                                window.location.href = "/yujing.html"
                            }, 200)

                            break;
                        case 7:
                            closeDiag()
                            setTimeout(() => {
                                // openFM("历史数据", 10, "SJDL_IFS_DATA.prj", "历史数据")
                                window.location.href = "/history.html"
                            }, 200)

                            break;
                        case 8:
                            closeDiag()
                            setTimeout(() => {
                                // openFM("历史数据", 10, "SJDL_IFS_DATA.prj", "历史数据")
                                window.location.href = "/dcsHistory.html"
                            }, 200)
                            break;
                        case 9:
                            closeDiag()
                            setTimeout(() => {
                                // openFM("预警阈值配置修改", 14, "SJDL_IFS_DATA.prj", "预警阈值配置修改")
                                window.location.href = "/canshushezhi.html"
                            }, 200)

                            break;
                        default:

                    }

                }
            }
        }
    }

    initEvent('zbf_foot_btns') //底部菜单 btns
    let frist = setInterval(() => {
        initValue();
        clearInterval(frist)
    }, 500)
    let timer = setInterval(() => {
        timsStover = true
        initValue()
    }, 1000 * 60)
    let oTodayTimer = setInterval(() => {
        document.getElementById("todayTimer").innerHTML = moment(new Date()).format('YYYY-MM-DD HH:mm:ss')
    }, 1000)


})()
